<template>
	<view class="content">
		<view v-if="isBindOk" >
			<uni-forms ref="baseForm" :rules="rules" :modelValue="baseFormData" label-position="top" label-width="200">
				<uni-forms-item label="姓名" required name="ownerName">
					<uni-easyinput v-model="baseFormData.ownerName" placeholder="请输入姓名" />
				</uni-forms-item>
				<uni-forms-item label="手机号" required name="mobile">
					<uni-easyinput :maxlength="11" v-model="baseFormData.mobile" placeholder="请输入手机号" />
				</uni-forms-item>
			</uni-forms>
			<u-button type="primary" @click="submit">订阅通知</u-button>
		</view>
		<view v-else>
		    已订阅成功
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isBindOk:true,
				baseFormData: {
					ownerName: '',
					mobile: "",
				},
				// 校验规则
				rules: {
					ownerName: {
						rules: [{
							required: true,
							errorMessage: '车主姓名不能为空'
						}]
					},
					mobile:{
						rules: [{
							required: true,
							errorMessage: '联系方式不能为空'
						}]
					}
				},
				source:'weixin',
				code:""
			}
		},
		onLoad(option){
			console.log(option);
			// #ifdef H5
			   this.source = "H5";
			   if(!option.code){
				   window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxad64095db985862d&redirect_uri='+window.location.href +'&response_type=code&scope=snsapi_base&state=123#wechat_redirect'
			   }else{
				    this.code = option.code;
			   }
			// #endif
		},
		methods: {
            init(){
				uni.request({
					url:"wx/getOauthInfo",
					method:"POST",
					data:{
						code:this.code,
					},
					success:(res) =>{
						console.log('getOauthInfo：', res);
						uni.request({
							url:"owner/getUserInfo",
							method:"POST",
							data:{
								officialOpenid:res.data.openid,
							},
							success:(res) =>{
								console.log('getUserInfo：', res.data.data);
								if(res.data.data){
									this.isBindOk = false;
								}
							}
						})
					}
				})
			},
			submit(){
				this.$refs.baseForm.validate().then(res=>{
					console.log('表单数据信息：', res);
					this.save();
				}).catch(err =>{
					console.log('表单错误信息：', err);
				})
			},
			save(){
				uni.request({
					url: "wx/getOpenid",
					method:"POST",
					data:{
						...this.baseFormData,
						code:this.code,
					},
					success:(res) =>{
						console.log(res);
						if(res.data.openid){
							this.isBindOk = false;
							uni.showToast({
								title: '订阅成功',
								duration: 2000,
							});	
						}else{
							uni.showToast({
								title: "小程序未注册或手机号不一致",
								duration: 2000,
							});	
						}
					}
				})
			}
		}
	}
</script>

<style scoped lang="less">
	.content {
		padding: 0 20rpx;
	}
</style>